package net.cyue.web.easyquery.provider.http.router.solon;

import net.cyue.web.easyquery.core.http.HTTPRequestBody;
import net.cyue.web.easyquery.core.http.HTTPRequestMethod;
import net.cyue.web.easyquery.core.http.adapter.AbstractHTTPRequest;
import org.noear.solon.core.handle.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SolonHTTPRequest extends AbstractHTTPRequest<Context> {

    private final Logger logger = LoggerFactory.getLogger(this.toString());

    public SolonHTTPRequest(Context context) {
        super(context);
    }

    @Override
    public String remoteAddress() {
        return this.request.remoteIp();
    }

    @Override
    public int remotePort() {
        return this.request.remotePort();
    }

    @Override
    public String url() {
        return this.request.url();
    }

    @Override
    public String uri() {
        return this.request.uri().toString();
    }

    @Override
    public String scheme() {
        return this.request.protocol();
    }

    @Override
    public HTTPRequestMethod method() {
        return HTTPRequestMethod.valueOf(this.request.method().toUpperCase());
    }

    @Override
    public HTTPRequestBody body() {
        try {
            return HTTPRequestBody.fromJSONString(this.request.body());
        } catch (IOException e) {
            this.logger.error(e.getMessage());
        }
        return new HTTPRequestBody();
    }

    @Override
    public String getHeader(String name) {
        return this.request.header(name);
    }

    @Override
    public String getParameter(String name) {
        return this.request.param(name);
    }

    @Override
    public String[] getParameterValues(String name) {
        return this.request.paramValues(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> map = new HashMap<>();
        Map<String, List<String>> paramMap = this.request.paramMap().toValuesMap();
        for (Map.Entry<String, List<String>> entry : paramMap.entrySet()) {
            map.put(entry.getKey(), entry.getValue().toArray(new String[0]));
        }
        return map;
    }
}
